from django.conf import settings
# Create your views here.
from . import models
from Goods.models import GoodsBase, Goodspackage
from django.http import JsonResponse
from rest_framework.views import APIView
from rest_framework import exceptions
from rest_framework import serializers
from rest_framework.authentication import BaseAuthentication
from rest_framework.pagination import CursorPagination, LimitOffsetPagination,PageNumberPagination

import os
import json
import base64
import random
import string
from captcha.image import ImageCaptcha  # 从image.py中导入ImageCaptchar类
from django.core.mail import send_mail, send_mass_mail, EmailMultiAlternatives

# 用户认证
from user.utils.auth import Authtication
from user.utils.permission import AdminPermission

# ***************************************************  公共方法 *************************************

def getColl(request,id):
    # 根据ID获取一条收藏表里面的数据
    # id = request.GET['GID'] 
    User = getUser(request)
    try:
        obj = models.User_Collection.objects.get(user= User,goodesID=id)
        return obj
    except:
        return False


def GoodsObj(request):
    # 根据ID获取商品基础数据
    goodsId = request.data['GID']
    Obj = models.GoodsBase.objects.get(id=goodsId)
    return Obj

def getUser(request):
    # 用户User_Account表的数据
    try:
        Token = request.META.get("HTTP_TOKEN")  # 获取用户token
        User = models.User_Token.objects.get(token=Token).user  # 获取用户对象
        return User
    except:
        print("token异常未登录时访问带TOKEN验证的接口 请记录此Ip")
        return False


def md5(user):
    import hashlib
    import time
    ctime = str(time.time())
    m = hashlib.md5(bytes(user, encoding='utf-8'))
    m.update(bytes(ctime, encoding='utf-8'))
    return m.hexdigest()


def updateToken(User_AccountObj, token):
    TokenObj = models.User_Token.objects.filter(user=User_AccountObj).first()
    if not TokenObj:
        models.User_Token.objects.create(user=User_AccountObj, token=token)
    else:
        models.User_Token.objects.filter(
            user=User_AccountObj).update(token=token)
# ***************************************************  公共方法结束 *************************************


class AuthView(APIView):
    """
    用户认证 获取token
    """
    authentication_classes = []
    permission_classes = []

    def post(self, request, *args, **kwargs):
        ret = {'code': 1000, 'msg': None}
        try:
            user = request.data['username']  # .POST.get('phone')
            pwd = request.data['password']  # POST.get('password')
            Obj = models.User_Account.objects.filter(
                username=user, password=pwd).first()
            if not Obj:
                ret['code'] = 1001
                ret['msg'] = '密码错误'
                return JsonResponse(ret)
            # 创建token
            token = md5(user)
            updateToken(Obj, token)
            ret['token'] = token
            ret['msg'] = '登录成功'
        except Exception as e:
            ret['code'] = 1002
            ret['msg'] = '登录失败'
        return JsonResponse(ret)


ORDER_DICT = {
    1: {'name': '苹果', 'age': 18, 'gender': '男'},
    2: {'name': '小米', 'age': 18, 'gender': '男'},
    3: {'name': '红米', 'age': 18, 'gender': '男'},
}


class OrderView(APIView):
    """
    订单业务
    """
    authentication_classes = [Authtication, ]
    permission_classes = [AdminPermission, ]

    def get(self, request, *args, **kwargs):
        ret = {'code': 1000, 'msg': None, 'data': None}
        # print(request.user)
        try:
            ret['data'] = ORDER_DICT
        except:
            pass
        return JsonResponse(ret)

# 获取用户信息


def GetInformation(request):
    ret = {}
    authentication_classes = [Authtication, ]
    Token = request.META.get("HTTP_TOKEN")
    userMsg = models.User_Token.objects.get(token=Token).user
    ret['role'] = userMsg.role
    ret['name'] = userMsg.username
    if userMsg.UserID:
        # print(userMsg.UserID.name)
        ret['name'] = userMsg.UserID.name
        ret['porteait'] = str(userMsg.UserID.porteait)
        ret['gender'] = userMsg.UserID.gender
        ret['email'] = userMsg.UserID.email
    ret['code'] = 2000
    json.dumps(ret)

    # try:

    # except:
    #     ret['code'] = 5000
    #     pass
    return JsonResponse(ret)
# 注册


class register(APIView):
    def post(self, request, *args, **kwargs):
        if request.method == 'POST':
            context = {}
            username = request.data['phoneno']
            password = request.data['password']
            try:
                user_data = models.User_Account.objects.get(username=username)
                context['code'] = 500
                context['msg'] = "账号已被注册"
            except:
                try:
                    code = request.data['checkCode'].lower()
                    # request.session['emailCode'].lower()
                    emailCode = models.VfCode.objects.get(
                        key=username).value.lower()
                    if code == emailCode:
                        # 写入数据库
                        models.User_Account.objects.create(
                            password=password, username=username, role="user")
                        context['state'] = True
                        context['code'] = 200
                        context['msg'] = '注册成功,请登录'
                        return JsonResponse(context)
                except:
                    context['code'] = 500
                    context['msg'] = '请先获取验证码'
        return JsonResponse(context)


class login(APIView):
    def post(self, request, *args, **kwargs):
        context = {}
        username = request.data['phone']  # .POST.get('phone')
        password = request.data['password']  # POST.get('password')
        user_data = models.User_Account.objects.get(username=username)
        try:
            user_data = models.User_Account.objects.get(username=username)
        except:
            context['message'] = "用户不存在！"
            return JsonResponse(context)

        if user_data.password == password:
            request.session['is_login'] = True
            context['is_login'] = True
            return JsonResponse(context)
        else:
            context['message'] = "密码错误！"
        return JsonResponse(context)
# 修改密码


def forget(request):
    context = {}
    username = request.POST.get('phoneno')
    password = request.POST.get('password')
    code = request.POST.get('code').lower()
    try:
        emailCode = request.session['emailCode'].lower()
    except:
        context['msg'] = "请重新获取验证码"
        return JsonResponse(context)
    if code == emailCode:
        try:
            userObj = models.User_Account.objects.get(username=username)
            userObj.password = password
            context['msg'] = "修改成功"
            context['code'] = 2000
            userObj.save()
        except:
            context['msg'] = "用户不存在"
    else:
        context['msg'] = "验证码错误"
    return JsonResponse(context)


def Information(request):
    context = {}
    return JsonResponse(context)

# 获取验证码


class getVerify(APIView):
    def get(self, request, *args, **kwargs):
        context = {}
        image = ImageCaptcha()
        code = random.sample(string.ascii_letters, 4)
        random_code = "".join(code)
        userkey = ''
        try:
            userkey = request.GET['key']
            obj = models.VfCode.objects.get(key=userkey)
            obj.value = random_code
            obj.save()
        except:
            userkey = md5(random_code)
            obj = models.VfCode(key=userkey, value=random_code)
            obj.save()
        data = image.generate(random_code)
        b64 = data.getvalue()
        json.dumps(context)
        base64_data = base64.b64encode(b64)
        context['code'] = userkey
        context['b64'] = str(base64_data)[:-1][2:]
        return JsonResponse(context)

# def getVerify(request):  # 使用了 coki


class ifVerify(APIView):
    def post(self, request, *args, **kwargs):
        context = {}
        userCode = request.data['code'].lower()
        try:
            userkey = request.data['key']
            dbcode = models.VfCode.objects.get(key=userkey).value.lower()
        except:
            context['state'] = False
            context['msg'] = '验证失败'
            return JsonResponse(context)
        context['msg'] = '验证成功'
        if userCode == dbcode:
            context['state'] = True
        else:
            context['state'] = False
            context['msg'] = '验证码不正确'
        return JsonResponse(context)

# 发送邮件


class send_email(APIView):
    def post(self, request, *args, **kwargs):
        context = {}
        try:
            isEmall = request.data['phoneno']
            code = "".join(random.sample(string.ascii_letters, 4))
            _A = models.VfCode.objects.filter(key=isEmall)
            if _A:
                _A[0].value = code.lower()
                _A[0].save()
            else:
                models.VfCode.objects.create(
                    key=isEmall, value=code.lower())
            request.session.set_expiry(60)
            try:
                res = send_mail('验证码',
                                '欢迎注册您的验证码为： %s' % code,
                                '2810201146@qq.com',
                                [isEmall])
                if res == 1:
                    context['code'] = 200
                    context['msg'] = '发送成功'
                else:
                    context['code'] = 500
                    context['msg'] = '发送失败,请重新发送!'
            except:
                context['code'] = 500
                context['msg'] = '发送失败,请重新发送!'
        except:
            context['code'] = 500
            context['msg'] = '500-发送失败,请重新发送!'

        return JsonResponse(context)



# 购物车
def ShopData(request):
    # 判断商品与商品套餐是否一致
    goods = GoodsBase.objects.get(id=request.data['goodsId'])  # 商品
    pake = Goodspackage.objects.get(id=request.data['packId'])
    if pake.Goods == goods.getDetailedObj():
        return {'goods':goods,'pake':pake}
    else:        
        return False
class ShoppingCartSer(serializers.ModelSerializer):
    name = serializers.CharField(source="Goods.title")
    imageShow = serializers.CharField(source="Goods.src")
    price = serializers.CharField(source="Goods.getPrice")
    goodsid = serializers.CharField(source="Goods.id")

    color = serializers.CharField(source="Goodspackage.colorID.title")
    typename = serializers.CharField(source="Goodspackage.speID.title")
    stock = serializers.IntegerField(source="Goodspackage.inventory")
    GoodspackageID = serializers.IntegerField(source="Goodspackage.id")
    num = serializers.IntegerField(source="number")

    class Meta:
        model = models.ShoppingCart
        fields = ['id','GoodspackageID','goodsid','name','imageShow', 'num','price','color','typename','stock']

class ShoppingCart(APIView):
    authentication_classes = [Authtication, ]
    def get(self, request, *args, **kwargs):
        '''
        
        '''
        User = getUser(request)
        obj = models.ShoppingCart.objects.filter(user=User)
        GoodsListSer = ShoppingCartSer(
            instance=obj, many=True).data  # 序列化 获取到相关数据
        return JsonResponse(GoodsListSer, safe=False)

    def post(self, request, *args, **kwargs):
        ret = {}
        ShopDataObj = ShopData(request)
        if ShopDataObj:
            dic = {
                'user':getUser(request),
                'Goods':ShopDataObj['goods'],
                'Goodspackage':ShopDataObj['pake'],
            }
            # 判断是否已经有了
            obj = models.ShoppingCart.objects.filter(**dic)
            number = int(request.data['number'])
            if obj and number>=0:
                obj[0].number =number + int(obj[0].number)
                obj[0].save()
            else:
                dic['number'] = request.data['number']
                models.ShoppingCart.objects.create(**dic)
            ret['state'] = 2000
            
        else:
            # 向系统提出警告
            ret['state'] = 5000
        return JsonResponse(ret, safe=False)

    def put(self, request, *args, **kwargs):
        ret = {}
        ShopDataObj = ShopData(request)
        if ShopDataObj:
            dic = {
                'user':getUser(request),
                'Goods':ShopDataObj['goods'],
                'Goodspackage':ShopDataObj['pake'],
            }
            obj = models.ShoppingCart.objects.filter(**dic)
            number = int(request.data['number'])
            if obj and number>=0:
                obj[0].number = number
                obj[0].save()
            # obj.number = request.data['number']
            # obj.update()
        else:
            # 向系统提出警告
            pass
        
        return JsonResponse(ret)

    def delete(self, request, *args, **kwargs):
        ret = {}
        idList = []
        idList = json.loads(request.data['id'])
        try:
            obj = models.ShoppingCart.objects.filter(id__in=idList).delete()
        except:
            # 向系统提出警告
            pass
        return JsonResponse(ret, safe=False)


# 收藏

class MyPageNumberPagination(PageNumberPagination):
    #自定义分页类
    #每页显示多少个
    page_size = 10
    #默认每页显示3个，可以通过传入pager1/?page=2&size=4,改变默认每页显示的个数
    page_size_query_param = "size"
    #最大页数不超过10
    max_page_size = 10
    #获取页码数的
    page_query_param = "page"
class CollectionSer(serializers.ModelSerializer):
    class Meta:
        model = models.User_Collection
        fields = "__all__"
class collection(APIView):
    authentication_classes = [Authtication, ]
    def get(self, request, *args, **kwargs):
        ret = {}
        User = getUser(request)
        roles = models.User_Collection.objects.filter(user=User)
        # 分页
        pg = MyPageNumberPagination()
        page_roles = pg.paginate_queryset(queryset=roles,request=request,view=self)
        # 序列化
        ser = CollectionSer(instance=page_roles,many=True).data
        ret['list'] = ser
        ret['max'] = len(roles) / pg.page_size
        return JsonResponse(ret, safe=False)
    def post(self, request, *args, **kwargs):
        # 添加收藏
        ret = {}
        Goodes = GoodsObj(request)
        User = getUser(request)
        dic = {
            'user': User,
            'goodesID': Goodes.id,
            'title':Goodes.title,
            'img':Goodes.src,
            'price':Goodes.getPrice()
        }
        models.User_Collection.objects.get_or_create(**dic)
        return JsonResponse(ret)
    def delete(self,request,*args,**kwargs):
        ret = {}
        try:
            Goodes = GoodsObj(request)
            User = getUser(request)
            models.User_Collection.objects.get(user=User,goodesID=Goodes.id).delete()
            ret['state'] = 2000
        except:
            ret['state'] = 4000
        return JsonResponse(ret)
def ifCOllection(request):
    # 是否收藏
    User = GoodsObj(request)
    models.User_Collection.objects.get
    # def put(self, request, *args, **kwargs):
# 加入购物车

# 从购物车删除

# 增加 或者 减少购买的数量

# 提交订单 生成订单
